<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="940px">
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户编码" prop="customerCode">
            <el-input v-model="form.customerCode" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户分类" prop="classificationId">
            <el-select v-model="form.classificationId" placeholder="客户分类" :disabled="isView" style="width:300px" @change="handleSelectClassify">
              <el-option v-for="(item,index) in customerItem" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="行业分类" prop="industryId">
            <el-select v-model="form.industryId" placeholder="行业分类" :disabled="isView" style="width:300px" @change="indexSelect($event)">
              <el-option v-for="(item,index) in industryItem" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户简称" prop="customerAbbrev">
            <el-input v-model="form.customerAbbrev" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户全称" prop="customerName">
            <el-input v-model="form.customerName" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮政编码">
            <el-input v-model="form.postalCode" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="form.contact" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="form.email" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位性质" prop="companyItemId">
            <el-select v-model="form.companyItemId" placeholder="单位性质" :disabled="isView" style="width:300px" @change="indexSelect($event)">
              <el-option v-for="(item,index) in comItem" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="注册资金（万元）">
            <el-input v-model="form.registeredCapital" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="法定代表人">
            <el-input v-model="form.head" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度">
            <el-input v-model="form.longtitude" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="纬度">
            <el-input v-model="form.latitude" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属地区" prop="country" :rules="{ required: true, message: '请选择所属地区', trigger: 'blur' }">
            <AreaSelect v-if="isDomestic" ref="areaSelect" :default-props="form" @change="handleSelectArea" />
            <AreaSelectForeign v-else ref="areaSelect" :default-props="form" @change="handleSelectArea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- <el-col :span="12">
                  <el-form-item label="服务等级" prop="serviceContent">
                    <el-input v-model="form.serviceContent" class="input_text" :readonly="isView" />
                  </el-form-item>
                </el-col>-->
        <el-col :span="12">
          <el-form-item label="状态" prop="state">
            <el-radio v-for="item in dicts" :key="item.id" v-model="form.state" :label="item.id" :disabled="isView">{{ item.name }}</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
      <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { add, edit } from '@/api/tCustomerInfo'
import AreaSelect from '@/components/AreaSelect'
import AreaSelectForeign from '@/components/AreaSelectForeign'
import { isvalidPhone, isvalidEmail } from '@/utils/validate'

export default {
  components: {
    AreaSelect,
    AreaSelectForeign
  },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const validEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱地址'))
      } else if (!isvalidEmail(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }
    return {
      title: '详情',
      loading: false,
      dialog: false,
      form: {
        id: '',
        customerCode: '',
        classificationId: '',
        classificationItemName: '',
        industryId: '',
        industryItemName: '',
        customerAbbrev: '',
        customerName: '',
        postalCode: '',
        address: '',
        contact: '',
        email: '',
        phone: '',
        companyItemId: '',
        companyItemName: '',
        registeredCapital: '',
        head: '',
        area: '',
        latitude: '',
        longtitude: '',
        serviceContent: '',
        state: 1,
        country: '',
        province: '',
        city: '',
        county: ''
      },
      dicts: [
        {
          id: 1,
          name: '有效'
        },
        {
          id: 2,
          name: '无效'
        }
      ],
      customerItem: [],
      comItem: [],
      industryItem: [],
      customerArea: [],
      rules: {
        classificationId: [
          { required: true, message: '请选择客户分类', trigger: 'blur' }
        ],
        customerCode: [
          { required: true, message: '请输入客户编码', trigger: 'blur' }
        ],
        industryId: [
          { required: true, message: '请选择行业分类', trigger: 'blur' }
        ],
        customerAbbrev: [
          { required: true, message: '请输入客户简称', trigger: 'blur' }
        ],
        customerName: [
          { required: true, message: '请输入客户全称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        email: [{ required: true, validator: validEmail, trigger: 'blur' }],
        phone: [{ required: true, validator: validPhone, trigger: 'blur' }],
        companyItemId: [
          { required: true, message: '请选择单位性质', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入所属地区', trigger: 'blur' }
        ],
        /* serviceContent: [
          { required: true, message: '请输入服务等级', trigger: 'blur' }
        ],*/
        state: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 是否国内客户
    isDomestic() {
      const item = this.customerItem.find(v => v.id === this.form.classificationId)
      return item && item.value === '2'
    }
  },
  created: function() {
    this.byNameinfo('客户类型', this.customerItem)
    this.byNameCominfo('单位性质', this.comItem)
    this.byNameIndustryIinfo('行业类型', this.industryItem)
    this.byNameAreaType('所属地区')
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    handleSelectClassify(e) {
      this.form.country = ''
      this.form.province = ''
      this.form.city = ''
      this.form.county = ''
    },
    handleSelectArea(countryItem, provinceItem, cityItem, areaItem) {
      this.form.country = countryItem.name
      this.form.province = provinceItem.name
      this.form.city = cityItem.name
      this.form.county = areaItem.name
      if (this.isDomestic) {
        this.form.area = `${this.form.country}/${this.form.province}/${this.form.city}/${this.form.county}`
      } else {
        this.form.area = `${this.form.country}/${this.form.province}`
      }
    },
    byNameAreaType(name) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.customerArea = resobject
        })
      })
    },
    byNameIndustryIinfo(name, industryItem) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.industryItem = resobject
        })
      })
    },
    byNameCominfo(name, comItem) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.comItem = resobject
        })
      })
    },
    byNameinfo(name, customerItem) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.customerItem = resobject
        })
        // 根据id再进行全部查询
      })
    },
    // 获取id值
    byName(name) {
      return request({
        url: 'api/dict/byName/' + name,
        method: 'get'
      })
    },
    // 获取id值
    bydictId(id) {
      if (id) {
        return request({
          url: 'api/dictDetail/findByDeptId/' + id,
          method: 'get'
        })
      }
    },
    // ----------------------
    indexSelect(event) {

    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else this.doEdit()
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      // 如果是国内用户，需要将选择的国家地区赋值给area
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.$refs['areaSelect'] && this.$refs['areaSelect'].clear()
      this.form = {
        id: '',
        customerCode: '',
        classificationId: '',
        classificationItemName: '',
        industryId: '',
        industryItemName: '',
        customerAbbrev: '',
        customerName: '',
        postalCode: '',
        address: '',
        contact: '',
        email: '',
        phone: '',
        companyItemId: '',
        companyItemName: '',
        registeredCapital: '',
        head: '',
        area: '',
        latitude: '',
        longtitude: '',
        /* serviceContent: '',*/
        state: '',
        country: '',
        province: '',
        city: '',
        county: ''
      }
    }
  }
}
</script>

<style scoped>
.input_text {
  width: 300px;
}
</style>
